<template>
  <div class="mesure">
    <el-icon class="close-icon" :size="18" :color="'#FF7071'" @click="deleteNode">
      <CircleCloseFilled />
    </el-icon>
    <Handle id="measure_b" type="target" :position="Position.Left" />
    <div class="ps-header">
      <div class="title">测点</div>
      <div class="expand-btn" @click="isExpand = !isExpand">{{ isExpand ? '收起' : '展开' }}</div>
    </div>
    <div class="ps-body" @mousedown.stop>
      <el-form ref="measureFormRef" :model="measureData" :rules="rules" label-width="90px">
        <el-form-item label="测点名称" prop="name">
          <el-input
            v-model="measureData.name"
            placeholder="请输入测点名称"
            @change="handleMeasureChange"
          />
        </el-form-item>
        <el-form-item label="信号数据" prop="signalIdList">
          <template #label>
            <div>
              <div>信号数据</div>
              <div style="font-size: 12px; line-height: 12px">(多选)</div>
            </div>
          </template>
          <el-select
            v-model="measureData.signalIdList"
            clearable
            multiple
            style="width: 100%"
            placeholder="请选择信号数据"
            @change="handleSginalChange"
          >
            <el-option
              v-for="item in signalList"
              :key="item.signalId"
              :label="item.signalLabel + '(' + item.signalSourceList + ')'"
              :value="item.signalId"
            />
          </el-select>
        </el-form-item>
        <template v-if="isExpand">
          <el-form-item label="X轴位置" prop="positionX">
            <el-input
              v-model="measureData.positionX"
              placeholder="请输入"
              @change="handleMeasureChange"
            />
          </el-form-item>

          <el-form-item label="Y轴位置" prop="positionY">
            <el-input
              v-model="measureData.positionY"
              placeholder="请输入"
              @change="handleMeasureChange"
            />
          </el-form-item>
          <el-form-item label="Z轴位置" prop="positionZ">
            <el-input
              v-model="measureData.positionZ"
              placeholder="请输入"
              @change="handleMeasureChange"
            />
          </el-form-item>
        </template>
      </el-form>
      <div style="height: 300px" v-if="isExpand">
        <DiagramPicker
          v-if="monitorDevice && monitorDevice.fileType === 2"
          v-model="measureData"
          :monitorDevice="monitorDevice"
          :otherPoints="allOtherMeasureNodes"
          @update:model-value="handleMeasureChange"
        />

        <ImagePicker
          v-if="monitorDevice && monitorDevice.fileType === 1"
          :monitorDevice="monitorDevice"
          :otherPoints="allOtherMeasureNodes"
          v-model="measureData"
          @update:model-value="handleMeasureChange"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { Handle, Position, useVueFlow, useNodeConnections, useNodesData } from '@vue-flow/core'
import { CircleCloseFilled } from '@element-plus/icons-vue'
import DiagramPicker from './DiagramPicker.vue'
import ImagePicker from './ImagePicker.vue'
import { FormInstance, FormRules } from 'element-plus'

const { updateNode, removeNodes, nodes, getSelectedEdges, removeSelectedEdges } = useVueFlow()

const props = defineProps<{
  node: any
  taskHook: any
}>()

const { sauInstanceMap, monitorDevice } = props.taskHook
const { node } = toRefs(props)

const measureData = ref<any>({
  signalIdList: [],
  signalList: [],
  name: '',
  positionX: '',
  positionY: '',
  positionZ: ''
})

const measureFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入测点名称', trigger: 'change' }],
  signalIdList: [{ required: true, message: '请选择信号数据', trigger: 'change' }]
})

const isExpand = ref(false)

if (node.value.data.measureData) {
  measureData.value = node.value.data.measureData
}

const sourceConnections = useNodeConnections({
  handleType: 'target'
})

const sauNodesData = useNodesData(() =>
  sourceConnections.value.map((connection) => connection.source)
)

/**
 * 获取任务中的其他监测点
 */
const allOtherMeasureNodes = computed(() => {
  return nodes.value.filter((item) => item.id !== node.value.id && item.type === 'output')
})

/**
 * 按 signalSourceList（转字符串）和 signalLabel 排序
 * @param {Array} data - 信号数组
 * @returns {Array} 排序后的数组
 */
function sortSignals(data) {
  return [...data].sort((a, b) => {
    const sourceA = a.signalSourceList.join(',')
    const sourceB = b.signalSourceList.join(',')

    if (sourceA < sourceB) return -1
    if (sourceA > sourceB) return 1

    return a.signalLabel.localeCompare(b.signalLabel)
  })
}

/**
 * 计算相连的已经生成了sau实例的所有信号输出
 */
const signalList = computed(() => {
  const signalArray: any[] = []
  sauNodesData.value.forEach((item) => {
    const sauInstanceId = item.data.sauInstanceId
    if (sauInstanceId) {
      const sauInstance = sauInstanceMap.value.get(sauInstanceId)
      if (sauInstance) {
        const outputSignalList = sauInstance.outputSignalList.length
          ? sauInstance.outputSignalList
          : []
        signalArray.push(...outputSignalList)
      }
    }
  })

  // 加上排序
  return sortSignals(signalArray)
})

/**
 * 当删除了实例，去除绑定的选中的信号数据
 * @param signalListArray
 */
const resolveSignalIdList = (signalListArray: any) => {
  const signalIdList: string[] = []
  measureData.value.signalIdList.forEach((item: string) => {
    const signal = signalListArray.find((signalItem) => signalItem.signalId === item)
    if (signal) {
      signalIdList.push(item)
    }
  })
  measureData.value.signalIdList = signalIdList
  handleSginalChange()
}

/**
 * 点位改变
 */
const handleSginalChange = () => {
  measureData.value.signalList = signalList.value.filter((item: any) => {
    return measureData.value.signalIdList.includes(item.signalId)
  })

  handleMeasureChange()
}

/**
 * 更新节点数据
 */
const handleMeasureChange = () => {
  updateNode(node.value.id, {
    data: {
      measureData: measureData.value
    }
  })
}

/**
 * 删除
 */
const deleteNode = () => {
  removeSelectedEdges(getSelectedEdges.value)
  removeNodes([node.value.id])
}

watch(
  () => signalList.value,
  (newVal) => {
    resolveSignalIdList(newVal)
  },
  {
    deep: true
  }
)
</script>
<style lang="scss" scoped>
.mesure {
  width: 500px;
  height: auto;
  cursor: pointer;

  .close-icon {
    position: absolute;
    top: -15px;
    right: -15px;
    font-size: 18px;
  }

  .ps-header {
    background: url('@/assets/task/task03.png') 12px center / 25px 25px no-repeat;
    padding: 4px 10px 4px 49px;
    color: #333;
    font-size: 14px;
    display: flex;
    justify-content: space-between;

    .expand-btn {
      color: #ff811a;
    }
  }

  .ps-body {
    padding: 10px 10px 0;
    cursor: default;
  }

  .vue-flow__handle {
    background-color: rgb(241, 136, 28);
    height: 24px;
    width: 8px;
    border-radius: 4px;
  }
}
</style>
